<template>
  <div class="CountingTask">
    <el-main>
      <div>
        <el-form ref="form" :model="form" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="盘点单状态">
                  <el-select v-model="taskSearchState" placeholder="全部" @change="searchState">
                    <el-option label="全部" value></el-option>
                    <el-option label="已完成" value="3 "></el-option>
                    <el-option label="未盘点" value="1"></el-option>
                    <el-option label="盘点中" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <div class="block">
                  <span class="demonstration">创建时间:</span>
                  <el-date-picker
                    v-model="start_end_date"
                    type="daterange"
                    @change="dateChange"
                    value-format="yyyy-MM-dd"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                  <!-- <el-button icon="el-icon-search"></el-button> -->
                </div>
              </div>
            </el-col>
          </el-row>
          <!-- </el-row>
          <el-row>-->
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-button @click="EditAsset" type="primary" class="EditAsset">编辑</el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                :plain="true"
                class="clear"
                @click="clear"
              >删除</el-button>
            </div>
          </el-col>
        </el-form>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData3"
        border
        stripe
        height="301"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="state" label="盘点状态" style="width: 20%" :formatter="inventoryState"></el-table-column>
        <el-table-column prop="name" label="任务单名称" style="width: 20%">
          <template slot-scope="scope">
            <el-button
              @click="taskNameClick(scope.row)"
              type="text"
              style="margin:0 auto"
            >{{scope.row.name}}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="createDate" label="创建时间" style="width: 20%"></el-table-column>
        <el-table-column prop="createUserName" label="创建人" style="width: 20%"></el-table-column>
        <el-table-column prop="operation" label="操作" style="width: 20%">
          <template slot-scope="scope">
            <el-button
              @click="operationClikck(scope.row)"
              type="success"
              style="margin:0 auto"
            >{{scope.row.state === 1 ? "开始盘点" : scope.row.state === 2 ? "结束盘点" : "重新盘点"}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        title="盘点任务单"
        width="80%"
        :visible.sync="dialogFormVisible"
        style="font-weight: 700;"
      >
        <el-form :model="form">
          <el-row>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="盘点单名称" :label-width="formLabelWidth" style="margin-right:20px">
                  <el-input v-model="bean.name" auto-complete="off">{{bean.name}}</el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple-light">
                <el-form-item label="分配用户">
                  <el-select v-model="form.userList1" multiple placeholder="用户" style="width:380px">
                    <el-option
                      v-for="item in list"
                      :key="item.id"
                      :label="item.username"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <hr>
          <br>
          <el-row>
            <el-col :span="14">
              <div class="grid-content bg-purple">
                <el-form-item>
                  <h2 style="font-size:18px;font-weight: 700;">待盘点任务单</h2>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="grid-content bg-purple">
                <el-form-item>
                  <el-button type="primary" @click="del">删除</el-button>
                  <!-- <el-button type="text" size="small" @click="addData">
                    <el-button type="primary" @click="innerVisible = true">添加资产</el-button>
                  </el-button>-->
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-dialog width="80%" title="添加资产" :visible.sync="innerVisible" append-to-body>
            <el-form-item>
              <el-row :gutter="20">
                <el-col :span="6">
                  <div class="grid-content bg-purple">
                    <el-input
                      placeholder="请输入关键字进行搜索"
                      v-model="input6"
                      class="input-with-select"
                      style="width:230px;margin:0 10px;"
                    >
                      <el-button slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="grid-content bg-purple">
                    <el-button type="primary">取消</el-button>
                    <el-button type="primary">确定</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
            <el-table
              ref="multipleTable"
              :data="tableData4"
              border
              stripe
              tooltip-effect="dark"
              style="width: 100%"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="state" label="状态" width="150" :formatter="formatState"></el-table-column>
              <el-table-column prop="pictureUrl" label="照片" width="120">
                <!-- 图片的显示 -->
                <template slot-scope="scope">
                  <img
                    v-if="scope.row.pictureUrl"
                    :src="requestUrl+scope.row.pictureUrl"
                    min-width="80"
                    height="80"
                    @click="lookBigImage(scope.row.pictureUrl)"
                  >
                </template>
              </el-table-column>
              <el-table-column prop="assetCode" label="资产编号" width="120"></el-table-column>
              <el-table-column prop="assetName" label="资产名称" width="120"></el-table-column>
              <el-table-column prop="standardType" label="规格" width="300"></el-table-column>
              <el-table-column prop="sn" label="SN号" width="120"></el-table-column>
              <el-table-column prop="unit" label="计量单位" width="120"></el-table-column>
              <el-table-column prop="amount" label="金额(单位:万元)" width="200"></el-table-column>
              <el-table-column prop="useCompany" label="使用公司" width="120"></el-table-column>
              <el-table-column prop="useDept" label="使用部门" width="120"></el-table-column>
              <el-table-column prop="buyDate" label="购入时间" width="120"></el-table-column>
              <el-table-column prop="useUser" label="使用人" width="120"></el-table-column>
              <el-table-column prop="ownCompany" label="所属公司" width="300"></el-table-column>
              <el-table-column prop="area" label="区域" width="120"></el-table-column>
              <el-table-column prop="storageLocation" label="存放地点" width="120"></el-table-column>
              <el-table-column prop="deadLine" label="使用期限(月)" width="120"></el-table-column>
              <el-table-column prop="assetAdmin" label="管理员" width="120"></el-table-column>
            </el-table>
          </el-dialog>
          <!-- <el-form-item></el-form-item> -->
          <el-table :data="gridData" ref="tempTable" border stripe @select="assetList2">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column property="state" label="盘点状态" :formatter="assetState"></el-table-column>
            <el-table-column property="assetCode" label="资产编号"></el-table-column>
            <el-table-column property="assetName" label="资产名称"></el-table-column>
            <el-table-column property="useOrganizationName" label="使用部门"></el-table-column>
            <el-table-column property="useUser" label="使用人"></el-table-column>
            <el-table-column property="createDate" label="购入时间"></el-table-column>
            <el-table-column property="ownOrganizationName" label="所属公司"></el-table-column>
            <el-table-column property="assetAdmin" label="管理员"></el-table-column>
            <el-table-column property="remark" label="备注"></el-table-column>
          </el-table>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 盘点任务单详情的弹框 -->
      <el-dialog
        title="盘点任务单"
        width="80%"
        :visible.sync="dialogTaskInfoVis"
        style="font-weight: 700;"
      >
        <el-form :model="taskInfo">
          <el-row>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="盘点单名称" style="margin-right:20px">
                  <span>{{taskInfo.taskName}}</span>
                </el-form-item>
              </div>
            </el-col>

            <el-col :span="12">
              <div class="grid-content bg-purple-light">
                <el-form-item label="分配用户" style="margin-right:20px">
                  <span>{{taskInfo.taskUser}}</span>
                </el-form-item>
              </div>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="4">
              <div class="grid-content bg-purple">
                <el-form-item label="创建人" style="margin-right:20px">
                  <span>{{taskInfo.createUser}}</span>
                </el-form-item>
              </div>
            </el-col>

            <el-col :span="4">
              <div class="grid-content bg-purple">
                <el-form-item label="盘点总数" style="margin-right:20px">
                  <span>{{taskInfo.total}}</span>
                </el-form-item>
              </div>
            </el-col>

            <el-col :span="4">
              <div class="grid-content bg-purple">
                <el-form-item label="盘盈" style="margin-right:20px">
                  <span>{{taskInfo.gain}}</span>
                </el-form-item>
              </div>
            </el-col>

            <el-col :span="4">
              <div class="grid-content bg-purple">
                <el-form-item label="盘亏" style="margin-right:20px">
                  <span>{{taskInfo.loss}}</span>
                </el-form-item>
              </div>
            </el-col>

            <el-col :span="4">
              <div class="grid-content bg-purple">
                <el-form-item label="创建时间" style="margin-right:20px">
                  <span>{{taskInfo.createDate}}</span>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <hr>
          <br>
          <el-table :data="taskInfo.taskInfoAssetList" border stripe>
            <el-table-column property="state" label="资产状态" :formatter="assetState"></el-table-column>
            <el-table-column property="assetCode" label="资产编号"></el-table-column>
            <el-table-column property="assetName" label="资产名称"></el-table-column>
            <el-table-column property="useOrganizationName" label="使用部门"></el-table-column>
            <el-table-column property="useUser" label="使用人"></el-table-column>
            <el-table-column property="createDate" label="购入时间"></el-table-column>
            <el-table-column property="ownOrganizationName" label="所属公司"></el-table-column>
            <el-table-column property="assetAdmin" label="管理员"></el-table-column>
            <el-table-column property="remark" label="备注"></el-table-column>
          </el-table>
        </el-form>

        <div class="block">
          <el-row :gutter="20">
            <el-col :span="4">
              <div class="grid-content bg-purple">
                <!-- <span class="demonstration">已选择0条</span> -->
              </div>
            </el-col>
            <el-col :span="10">
              <div class="grid-content bg-purple">
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage4"
                  :page-sizes="[10, 20, 30, 40]"
                  :page-size="10"
                  layout="prev, pager, next, sizes, jumper"
                  :total="this.total"
                ></el-pagination>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-dialog>

      <br>
      <div class="block">
        <el-row :gutter="20">
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <!-- <span class="demonstration">已选择0条</span> -->
            </div>
          </el-col>
          <el-col :span="10">
            <div class="grid-content bg-purple">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage4"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="10"
                layout="prev, pager, next, sizes, jumper"
                :total="this.total"
              ></el-pagination>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-main>
  </div>
</template>
<script>
import { axiosPost, axiosGet, requestUrl } from "@/api/index.js";
import { constants } from "crypto";
export default {
  data() {
    return {
      keywords: "",
      requestUrl: requestUrl,
      form: {
        state: "",
        name: "",
        createDate: "",
        createUserName: "",
        operation: "",
        assetType: "",
        assetName: "",
        department: "",
        status: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        userList1: [],
        resource: "",
        desc: ""
      },
      bean: {}, //选中的条目的对象
      page: 1,
      pageSize: 10,
      scarchContent: "",
      total: 0,
      tableData3: [],
      tableData4: [],
      gridData: [],
      input6: "",
      start_end_date: [], //时间选择器
      taskSearchState: "", //搜索时的任务单状态
      currentPage1: 5,
      currentPage2: 5,
      currentPage3: 5,
      currentPage4: 1,
      taskList: [],
      list: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      dialogTaskInfoVis: false, //盘点任务单详情的弹框
      outerVisible: false,
      innerVisible: false,
      formLabelWidth: "120px",
      updateBean: {
        //这个对象是需要操作的对象    删除资产需要上传删除的资产id  添加也是同理   需要盘点任务单id   盘点任务单名称
        deleteAssetList: [],
        addAssetList: [],
        name: "",
        userList: [],
        taskId: ""
      },
      taskInfo: {
        //点击盘点任务单名称之后的弹框内容
        taskName: "", //盘点任务单的名称
        taskUser: "", //盘点任务单的分配用户
        taskId: "", //盘点任务单的名称
        taskInfoAssetList: [], //盘点任务单里面的资产列表
        gain: "", ///盘盈
        loss: "", //盘亏
        total: "", //总数
        createDate: "", //创建时间
        createUser: "" //创建人
      }
    };
  },
  beforeMount() {
    //调用封装好的函数,获取页面数据
    this.getList();
    //获取员工列表接口
    axiosGet("Account/GetStaffList", null).then(res => {
      if (res.status === 200 && res.data.success) {
        this.list = res.data.data;
      }
    });
  },
  methods: {
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //盘点任务单选中条数
    handleSelectionChange(val) {
      this.taskList = val;
      // console.log(this.taskList);
    },
    //待盘点任务单选中条数
    assetList(val) {
      this.assetList = val;
      // console.log(this.assetList);
    },
    handleSizeChange(val) {
      // console.log(val);
      this.pageSize = val;
    },
    //调用封装好的函数,分页加载数据
    handleCurrentChange(val) {
      this.page = val;
      // console.log(`当前页: ${val}` + "this.page = " + this.page);
      this.getList();
    },
    open() {
      this.$message("请至少选择一条盘点任务");
    },
    //删除盘点任务单接口
    clear() {
      let notFinishNum = 0; //未完成的个数
      this.taskList.forEach(item => {
        var state = item.state;
        if (state == 3 || state == 2) {
          notFinishNum += 1;
        }
      });

      if (notFinishNum > 0) {
        this.$message.error("盘点中或已完成的任务单不能删除!");
      } else if (this.taskList.length == 0) {
        this.$message.error("请选择需要删除的任务单!");
      } else {
        this.$confirm("你确定要删除该盘点任务单吗？", "删除盘点任务单", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            let delIdList = [];
            this.taskList.forEach(item => {
              delIdList.push({ id: item.id });
            });
            axiosPost("/Task/DeleteTask", {
              taskList: JSON.stringify(delIdList)
            }).then(res => {
              if (res.status === 200 && res.data.success) {
                // 删除成功了重新获取资产列表接口数据
                this.getList();
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
              } else {
                this.$message({
                  type: "error",
                  message: "删除失败!"
                });
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      }
    },

    //盘点任务单的状态
    inventoryState: function(row, column) {
      return row.state === 1 ? "未开始" : row.state === 2 ? "盘点中" : "已完成";
    },

    //盘点任务单的名称点击
    taskNameClick(item) {
      // this.taskInfo = {}; //因为是弹框所以需要清空里面的数据   不然界面会出现之前的数据之后才执行下面的数据
      this.dialogTaskInfoVis = true; //弹出一个框
      this.taskInfo.taskId = item.id;

      var bean = {
        userId: localStorage.getItem("userId"),
        taskId: this.taskInfo.taskId
      };
      axiosGet("Task/GetTaskUsers", bean).then(res => {
        if (res.status == 200 && res.data.success) {
          if (res.data.success) {
            // console.log(res.data.data);
            var names = "";
            for (var i = 0; i < res.data.data.length; i++) {
              names = names + res.data.data[0].name + ",";
            }
            var _name = names;
            if (names.length > 1) {
              _name = names.substr(0, names.length - 1);
            }
            this.taskInfo.taskUser = _name;
          } else {
            this.$message({
              type: "fail",
              message: "获取盘点任务单详情失败!"
            });
          }
        }
      });

      var bean = {
        userId: localStorage.getItem("userId"),
        id: this.taskInfo.taskId
      };
      axiosGet("Task/GetOneTask", bean).then(res => {
        if (res.status == 200 && res.data.success) {
          if (res.data.success) {
            this.taskInfo.taskName = res.data.data.name;
            this.taskInfo.gain = res.data.data.gain;
            this.taskInfo.loss = res.data.data.loss;
            this.taskInfo.createUser = res.data.data.createUserName;
            try {
              var date = res.data.data.createDate;
              var da = date.split("T");
              this.taskInfo.createDate = da[0];
            } catch (e) {
              this.taskInfo.createDate = res.data.data.createDate;
            }
            this.taskInfo.total = res.data.data.total;
            this.getTaskInfoAssetList();
          } else {
            this.$message({
              type: "fail",
              message: "获取盘点任务单详情失败!"
            });
          }
        }
      });
    },

    lookBigImage(imageUrl) {
      // this.dialogImageVisible=true;
      // this.showImageUrl= "http://wxtest.trfriend.com:12135/"+imageUrl;
    },
    //获取盘点任务单详情里面的资产列表
    getTaskInfoAssetList: function() {
      var bean = {
        page: 1,
        pageSize: 10,
        taskId: this.taskInfo.taskId,
        state: "",
        userId: localStorage.getItem("userId")
      };

      axiosGet("Task/GetTaskDetail", bean).then(res => {
        if (res.status == 200 && res.data.success) {
          if (res.data.success) {
            this.taskInfo.taskInfoAssetList = res.data.data.list;
          } else {
            this.$message({
              type: "fail",
              message: "获取盘点任务单资产列表失败!"
            });
          }
        }
      });
    },

    //每一条的盘点任务单后面的按钮的点击事件
    operationClikck(item) {
      // console.log(item);
      var taskId = item.id;
      if (item.state === 1) {
        this.updateTaskState(taskId, 2); //当state为1的时候任务单为未开始  点击之后就是把状态改成2盘点中
        this.$message({
          message: "盘点任务已启动",
          type: "success"
        });
      } else if (item.state === 2) {
        this.updateTaskState(taskId, 3);
        this.$message({
          message: "盘点任务已结束",
          type: "success"
        });
      } else if (item.state === 3) {
        this.updateTaskState(taskId, 1);
        this.$message({
          message: "已开启重盘任务",
          type: "success"
        });
      }
    },

    //改变盘点任务单的状态
    updateTaskState: function(taskId, state) {
      var bean = { taskId: taskId, state: state };
      axiosGet("Task/UpdateTaskState", bean).then(res => {
        if (res.status == 200 && res.data.success) {
          // console.log(res.data);
          this.getList();
        }
      });
    },

    //将数据库对应的数字转换成在用 闲置 报废
    formatState: function(row, column) {
      return row.state === 1 ? "未完成" : row.state === 2 ? "已完成" : "盘点中";
    },

    //资产盘点的状态
    assetState: function(row, column) {
      //盘点状态   0表示未盘，  1表示正常 2表示异常   3表示损坏   4表示盘盈  5表示盘亏
      var state = "";
      if (row.checkState === 5) {
        state = "盘亏";
      } else if (row.checkState === 1) {
        state = "正常";
      } else if (row.checkState === 2) {
        state = "异常";
      } else if (row.checkState === 3) {
        state = "损坏";
      } else if (row.checkState === 4) {
        state = "盘盈";
      } else {
        state = "未盘";
      }
      return state;
    },

    //获取盘点任务单列表接口封装起来
    getList: function() {
      var startDate = this.start_end_date
        ? this.start_end_date[0]
          ? this.start_end_date[0]
          : ""
        : "";
      var endDate = this.start_end_date
        ? this.start_end_date[1]
          ? this.start_end_date[1]
          : ""
        : "";
      var bean = {
        page: this.page,
        pageSize: this.pageSize,
        type: "",
        startDate: startDate,
        endDate: endDate,
        state: this.taskSearchState
      };
      axiosGet("/Task/GetTaskList", bean).then(res => {
        if (res.status == 200 && res.data.success) {
          var list = res.data.data.list;
          for (var i = 0; i < list.length; i++) {
            var createDate = list[i].createDate;
            // console.log(createDate);
            // try {
            var splite = createDate.split("T");
            console.log(splite);
            list[i].createDate = splite[0];
            // } catch (e) {
            //   list[i].createData = createData;
            // }
          }
          // console.log(list);

          this.tableData3 = list;
          this.total = res.data.data.total;
        }
      });
    },

    //编辑
    EditAsset() {
      // console.log(this.taskList.length);
      if (this.taskList.length == 0) {
        this.$message.error("请选择需要编辑的盘点任务单!");
      } else if (this.taskList.length >= 2) {
        this.$message.error("请选择一条盘点任务单!");
      } else {
        //将获取到的盘点任务单名称渲染到页面上
        this.bean = this.taskList[0]; //定义一个空数组,将获取到的名称赋值给数组
        // console.log(this.bean);
        if (this.bean.state === 2) {
          this.$message.error("盘点中的资产不可以编辑!");
          return;
        }

        var taskId = this.bean.id;
        this.dialogFormVisible = true;
        axiosGet(
          "/Task/GetTaskDetail?pageSize=" +
            this.pageSize +
            "&page=" +
            this.page +
            "&taskId=" +
            taskId
        ).then(res => {
          if (res.status == 200 && res.data.success) {
            this.gridData = res.data.data.list;
          }
        });
      }
    },

    assetList2(selection, row) {
      //得到选中的条目
      this.assetList = selection;
      // console.log(this.assetList); //选中的所有条目数组
    },

    //时间改变之后的回调
    dateChange() {
      // console.log(this.start_end_date);
      this.getList();
    },

    //搜索状态的回调
    searchState() {
      // console.log(this.taskSearchState);
      this.getList();
    },

    //删除待盘点任务单
    del() {
      let delIdList = [];
      // this.gridData=this.gridData.splice(0,1);

      // console.log(this.assetList);
      this.assetList.forEach(item => {
        // debugger;
        //this.assetList就是选中的资产数组
        delIdList.push({ id: item.id });
        this.gridData = this.gridData.filter(temp => {
          return temp.id != item.id;
        });
      });
      this.$refs.tempTable.clearSelection();
      this.updateBean.deleteAssetList = delIdList;
    },

    //获取资产列表数据接口用函数封装起来
    getAssetList: function() {
      var key1 = this.keywords;
      var bean = {
        page: this.page,
        pageSize: this.pageSize,
        key: key1,
        userId: localStorage.getItem("userId")
      };

      axiosGet("/Asset/GetAssetList", bean).then(res => {
        if (res.status == 200 && res.data.success) {
          var newList = res.data.data.list;
          this.gridData.forEach(item => {
            //this.assetList就是选中的资产数组
            newList = newList.filter(temp => {
              return temp.id != item.id;
            });
          });
          // console.log(newList);
          this.tableData4 = newList; //这里返回的newList就是去掉上一个界面传递过来的数据
          this.total = res.data.data.total;
        }
      });
    }
    /* //添加资产接口
    addData() {
      //添加资产的弹框  调用资产列表的接口
      this.getAssetList();
    } */
  }
};
</script>
<style lang="scss" scoped>
.CountingTask {
  height: 100%;
}
</style>
